package de.slothsoft.wasbinich.swingclient.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class GlobalEventHandler {

    private static GlobalEventHandler instance = new GlobalEventHandler();

    public static GlobalEventHandler getGlobalInstance() {
	return instance;
    }

    private final Map<String, List<GlobalListener>> globalListeners = new HashMap<>();

    protected GlobalEventHandler() {
	// hide from sight
    }

    public void register(String scope, GlobalListener listener) {
	getNullSafeGlobalListeners(scope).add(listener);
    }

    public void unregister(String scope, GlobalListener listener) {
	List<GlobalListener> listeners = getGlobalListeners(scope);
	if (listeners != null) {
	    listeners.remove(listener);
	    if (listeners.isEmpty()) {
		this.globalListeners.remove(scope);
	    }
	}
    }

    public void fireEvent(GlobalEvent event) {
	List<GlobalListener> listeners = getGlobalListeners(event.getScope());
	if (listeners != null) {
	    for (GlobalListener listener : listeners.toArray(new GlobalListener[listeners.size()])) {
		listener.handleEvent(event);
	    }
	}
    }

    protected Map<String, List<GlobalListener>> getAllGlobalListeners() {
	return this.globalListeners;
    }

    protected List<GlobalListener> getNullSafeGlobalListeners(String scope) {
	List<GlobalListener> listeners = getGlobalListeners(scope);
	if (listeners == null) {
	    listeners = new ArrayList<>();
	    this.globalListeners.put(scope, listeners);
	}
	return listeners;
    }

    protected List<GlobalListener> getGlobalListeners(String scope) {
	return this.globalListeners.get(scope);
    }

}
